<?php
namespace App\Utilities;

use App\Jobs\Fun;
use App\Models\UploadPicModel;

class Upload
{
    /**
     * 上传工具类
     */

    /**
     * 上传Excel返回图片地址
     * @return string
     */
    public static function uploadExcel($request,$imgName='excel')
    {
        $uploadSizeLimit = 10 * 1024 * 1023;//限制上传图片尺寸10M
        if(isset($_FILES[$imgName])){//判断图片存在
            if ($_FILES[$imgName]['size'] > $uploadSizeLimit) {
                echo "<script>alert('文件过大！');history.go(-1);</script>";exit;
            }
            $file = $request->file($imgName);           //获取图片
            return self::uploadLocalExcel($file);         //存储到本地
        } else {
            return '';
        }
    }

    /**
     * 这里是上传到本地
     * 上传方法，并处理文件
     * @return string
     */
    public static function uploadLocalExcel($file)
    {
        if($file->isValid()){
            if (!in_array($file->getClientOriginalExtension(),['xlsx','xls'])) {
                echo "<script>alert('你的文件格式不对！');history.go(-1);</script>";exit;
            }
            $extension       = $file->getClientOriginalExtension() ?: 'png';
            $folderName      = '/uploads/excels/';
            $destinationPath = public_path().$folderName;
            $safeName        = date('YmdHis',time()).rand(10,100).'.'.$extension;
            $file->move($destinationPath, $safeName);
            return $folderName.$safeName;
        } else {
            return "";
        }
    }

    /**
     * 通过接口上传图片到本地，返回图片地址
     * @return string
     */
    public static function uploadImgByApi($request,$imgName='file',$isyuantu=false)
    {
        $uploadSizeLimit = 10 * 1024 * 1023;//限制上传图片尺寸10M
        $suffix_img = [//图片允许后缀
            "png", "jpg", "gif", "bmp", "jpeg", "jpe",
        ];
       // var_dump($request);exit;
        if(isset($_FILES[$imgName])){//判断图片存在$request->hasFile($imgName)
            if ($_FILES[$imgName]['size'] > $uploadSizeLimit) {
                return array('code'=>-2,'msg'=>'图片过大！');
            }
            $file = $request->file($imgName);           //获取图片
            if($file->isValid()){
                if ($file->getClientOriginalExtension() &&
                    !in_array($file->getClientOriginalExtension(), $suffix_img)) {
                    return array('code'=>-3,'msg'=>'图片格式错误！');
                }
                $extension       = $file->getClientOriginalExtension() ?: 'png';
                $folderName      = '/uploads/'.date('Ymd', time()).'/';//图片的目录
                $destinationPath = public_path().$folderName;
                $safeName        = uniqid().'.'.$extension;
                $file->move($destinationPath, $safeName);

                $yuantuImgFilePath=$destinationPath.$safeName;
            ///    $yuantuUrlImg=$folderName.$safeName;

                $md5=md5_file($yuantuImgFilePath);////原图的
                $filePath=UploadPicModel::getFilePath($md5);
                if($filePath){
                    unlink($yuantuImgFilePath);//删除原图
                    return array(
                        'code' => 0,
                        'filePath' =>Fun::pImg($filePath[UploadPicModel::TypeSmall]),
                        'big' =>Fun::pImg($filePath[UploadPicModel::TypeBig]),
                    );
                }
                $big=$md5.UploadPicModel::TypeBig.'.'.$extension;///大图的文件名
                $sm=$md5.UploadPicModel::TypeSmall.'.'.$extension;///小图的文件名

                if($isyuantu) {
                    /*(new Imgcompress($yuantuImgFilePath, 0.9))->compressImg(
                        $destinationPath . $big);*/
                    copy($yuantuImgFilePath,$destinationPath . $big);
                }else{
                    (new Imgcompress($yuantuImgFilePath, 0.8))->compressImg(
                        $destinationPath . $big);
                }

                (new Imgcompress($yuantuImgFilePath,0.3))->compressImg(
                    $destinationPath.$sm);
                unlink($yuantuImgFilePath);//删除原图
                UploadPicModel::addPic($md5,$folderName,$extension);

               //  var_dump($yuantuImgFilePath,$yuantuUrlImg);exit;
                return array(
                    'code' => 0,
                    'filePath' =>Fun::pImg($folderName.$sm),
                    'big' =>Fun::pImg($folderName.$big),
                );
            }
        } else {
            return array('code'=>-1,'上传错误！');
        }
    }

    /**
     * 通过上传图片到本地，返回图片地址
     * @return string
     */
    public static function uploadImg($request,$imgName='file')
    {
        $uploadSizeLimit = 10 * 1024 * 1023;//限制上传图片尺寸10M
        $suffix_img = [//图片允许后缀
            "png", "jpg", "gif", "bmp", "jpeg", "jpe",
        ];
        if($request->hasFile($imgName)){//判断图片存在
            if ($_FILES[$imgName]['size'] > $uploadSizeLimit) {
                return array('code'=>-2,'msg'=>'图片过大！');
            }
            $file = $request->file($imgName);           //获取图片
            if($file->isValid()){
                if ($file->getClientOriginalExtension() &&
                    !in_array($file->getClientOriginalExtension(), $suffix_img)) {
                    return array('code'=>-3,'msg'=>'图片格式错误！');
                }
                $extension       = $file->getClientOriginalExtension() ?: 'png';
                $folderName      = '/uploads/'.date('Ymd', time()).'/';
                $destinationPath = public_path().$folderName;
                $safeName        = uniqid().'.'.$extension;
                $file->move($destinationPath, $safeName);
                return array(
                    'code' => 0,
                    'filePath' =>Fun::pImg($folderName.$safeName),
                );
            }
        } else {
            return array('code'=>-1,'上传错误！');
        }
    }

    /**
     * 文件转base64输出
     * @param $filePath 文件路径
     */
    public static function getBase64ByPath($filePath)
    {
        if(file_exists($filePath)){
            $mimeType = mime_content_type($filePath);
            $base64Data = base64_encode(file_get_contents($filePath));
            return 'data:'.$mimeType.';base64,'.$base64Data;
        }
        return '';
    }

    /**
     * 将Base64图片转换为本地图片并保存
     * @param  $base64 base64图片码，$camIp摄像头IP
     */
    public static function getPathByBase64($base64,$camIp='')
    {
        $camIp = $camIp ? $camIp : '192.168.1.1';
        $prefix2 = 'uploadSpots/'.$camIp.'/';
        if(!file_exists($prefix2)){ mkdir($prefix2, 0700); exec("cd ".$prefix2); }
        $prefix = $prefix2.date('Ymd',time()).'/';
        if(!file_exists($prefix)){ mkdir($prefix, 0700); }
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
            $type = $result[2];
            $prefix = $prefix . time() . '.' . $type;
            $resPut = file_put_contents($prefix, base64_decode(str_replace($result[1], '', $base64)));
            return $resPut ? $prefix : '';
        } else {
            // return '';
            $prefix = $prefix . time() . '.jpg';
            $resPut = file_put_contents($prefix, base64_decode($base64));
            return $resPut ? $prefix : '';
            // $fp = fopen($prefix, "wb");
            // fwrite($fp, base64_decode($base64)); fclose($fp);
            // return $prefix;
        }
    }
}